Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode mergeKLists(ListNode[] lists) {
  11. ListNode f = new ListNode(0);
  12. ListNode p = f;
  13. int k = lists.length;
  14. PriorityQueue<ListNode> heap = new PriorityQueue<>(k + 1, new Comparator<ListNode>() {
  15. public int compare(ListNode a, ListNode b) {
  16. return a.val - b.val;
  17. }
  18. });
  19. // step 1. put the first node of every list to the min heap
  20. for (int i = 0; i < k; i++) {
  21. if (lists[i] != null) {
  22. heap.offer(lists[i]);
  23. }
  24. }
  25. while (!heap.isEmpty()) {
  26. ListNode node = heap.poll();
  27. p.next = node;
  28. p = p.next;
  29. if (node.next != null) {
  30. heap.offer(node.next);
  31. }
  32. }
  33. p.next = null;
  34. return f.next;
  35. }
  36. }